// 路径转base64
import { base64ToPath } from './image-tools'
/**
 * 绘制类型
 */
export const TYPES = ['2d', 'webgl']

/**
 * 下载网路图片资源
 * @param { String } url 图片路径
 * @param { Object } options 参数
 * @returns 
 */
export const downloadFile = (url, options = {}) => {
	return new Promise(resolve => {
		const { header = {}, onProgressUpdate = () => {} } = options
		try {
			const download = uni.downloadFile({
				url,
				header,
				success: res => {
					return resolve({
						success: true,
						data: res
					})
				},
				fail: err => {
					return resolve({
						success: false,
						message: `下载资源${url}失败---${JSON.stringify(err)}`
					})
				}
			})
			// 下载进度回调
			download.onProgressUpdate(data => {
				onProgressUpdate(data)
			})
		} catch(e) {
			return resolve({
				success: false,
				msg: `下载资源${url}失败---${JSON.stringify(e)}`
			})
		}
	})
}

/**
 * base64转本地路径
 * @param { String } path 路径
 * @returns 
 */
export const base64ToPathFn = path => {
	const reg =
		/^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i
	if (!reg.test(path)) {
		return Promise.resolve(path)
	}
	return base64ToPath(path)
}

/**
 * 计算文字长度
 * @param { CanvasText } Context Context
 * @param { String } text 文本
 * @param { String } fontSize 文字大小
 * @returns 
 */
export const countTextLength = (Context, text, fontSize) => {
	const length = Context.measureText(text).width || 0
	if (length != 0) {
		return length
	}
	return text.length * fontSize
}

/**
 * rpx单位转换为px
 * @param { String | Number } size 单位大小
 * @returns 
 */
export const rpxToPx = size => {
	let type = false
	if (size.includes('px') && !size.includes('r') && !size.includes('u')) {
		size = Number(size.split('px')[0])
		type = true
	}else if (size.includes('rpx')) {
		size = Number(size.split('rpx')[0])
	} else if (size.includes('upx')) {
		size = Number(size.split('upx')[0])
	}
	return type ? size : uni.upx2px(size) 
}

/**
 * px单位转换成rpx单位
 * @param { String } size 单位大小
 * @returns 
 */
const pxToRpx = size => {
	return size / (uni.upx2px(100) / 100)
}

/**
 * 转换单位
 * @param { Object } params 转换单位
 */
export const conversionUnit = (params, getUnit, _this) => {
	const filterAttrs = ['quality', 'alpha', 'deg', 'zIndex', 'e', 's', 'drawImage']
	// const borderAttrs = ['borderWidth', 'lineWidth']
	const filterObject = () => {
		const datas = Object.assign({}, params)
		Object.keys(params).forEach(item => {
			const value = params[item]
			if (!filterAttrs.includes(item)) {
				if (typeof value === 'number') {
					if (value !== 375.0001) {
						datas[item] = getUnit.call(_this, value)
					}
				}
				if (typeof value === 'object' && !value instanceof Array) {
					datas[item] = conversionUnit(datas[item], getUnit, _this)
				}
				if (value instanceof Array) {
					datas[item] = value.map(item => typeof item === 'number' ? getUnit.call(_this, item) : item)
				}
			}
		})
		return datas
	}
	const filterArray = () => params.map(item => conversionUnit(item, getUnit, _this))
	if (!(params instanceof Array)) {
		return filterObject()
	} else {
		return filterArray()
	}
}


/**
 * 保存图片到相册
 * @param { String } filePath 图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
 * @returns 
 */
export const saveImageToPhotosAlbum = filePath => {
	return new Promise(resolve => {
		uni.showLoading({ title: '保存中...' })
		uni.saveImageToPhotosAlbum({
			filePath,
			success: res => {
				uni.hideLoading()
				resolve({
					success: true,
					data: res.file
				})
			},
			fail: err => {
				uni.hideLoading()
				resolve({
					success: false,
					message: err
				})
			}
		})
	})
}